<template>
  <div :style="`width:${!showMobileIcon ? '100%' : ''}`">
    <template v-if="!showMobileIcon">
      <div :class="{'mobile-input-component':showMobilePage && lineFeed}" class="select-input-component">
        <div class="filter-input">
          <el-input
            v-model.trim="value[selectKey]"
            :maxlength="100"
            :class="{'select-input-focus':inputFocus}"
            clearable
            size="small"
            placeholder="请输入内容"
            class="input-width-select input-width-select-bg"
            @focus="inputFocus = true"
            @blur="inputFocus = false"
            @clear="queryClick"
            @keyup.enter.native="queryClick">
            <el-select slot="prepend" v-model="selectKey" size="small" placeholder="请选择" class="changeStatus" popper-class="global-select-down" @change="normalChange" >
              <template v-for="item in filterList">
                <el-option
                  v-if="item.type === 'input'"
                  :key="item.keyword"
                  :label="item.name"
                  :value="item.keyword" />
              </template>
            </el-select>
            <div slot="append" class="filter-input-search" @click="queryClick">
              <i class="el-icon-search"/>
            </div>
          </el-input>
        </div>
        <template>
          <div v-if="showAdvancedFilter" class="operate-btn" @click="changeLevel">
            <!-- 高级 -->
            <el-tooltip :open-delay="500" content="高级筛选" placement="top">
              <div class="filter-box">
                <img :src="advancedFilterIcon" class="operate-icon" alt="">
                <span class="filter-label">高级</span>
              </div>
            </el-tooltip>
          </div>
          <PresetFilter
            v-if="isShowConfig"
            ref="PresetFilterRef"
            :select-value-result="selectValueResult"
            :get-preset-filter="getPresetFilter"
            :preset-type="1"
            is-resource
            use-scope-slot
            @queryClick="queryClick"
            @createNew="createNew" >
            <template slot-scope="scope" >
              <div :class="{'active': scope.visible}" class="operate-btn">
                <!-- 预设 -->
                <el-tooltip :open-delay="500" content="快捷筛选" placement="top">
                  <div class="filter-box">
                    <img :src="scope.visible?presetFilterIconActive:presetFilterIcon" class="operate-icon" alt="">
                    <span class="filter-label">快速</span>
                  </div>
                </el-tooltip>
              </div>
            </template>
          </PresetFilter>
          <div v-if="showReset" class="operate-btn" @click="queryEmpty">
            <el-tooltip :open-delay="500" content="重置筛选" placement="top">
              <div class="filter-box">
                <img :src="resetFilterIcon" class="operate-icon" alt="">
                <span class="filter-label">重置</span>
              </div>
            </el-tooltip>
          </div>
        </template>
        <slot name="input-after"/>
      </div>
      <div class="content">
        <template v-if="showFilterTag">
          <div class="tag-container">
            <template v-for="(item, index) in selectValueResult">
              <el-tag v-if="index <= 2" :key="index" class="filter-tag-group" type="info" disable-transitions>
                <div class="flex">
                  <span class="input-name">{{ item.name }}：</span>
                  <ToolTip :content="item.value" style="max-width: 12em" />
                  <div class="filter-tag-close" @click="deleteTag(item)">
                    <i class="el-tag__close el-icon-close" />
                  </div>
                </div>
              </el-tag>
            </template>
            <div class="filter-icon">
              <div v-if="selectValueResult.length && selectValueResult.length > 3" class="selected" @click="changeLevel">+{{ selectValueResult.length - 3 }}</div>
              <ToolTip v-if="isShowConfig" :show-copy-btn="false" content="保存快捷筛选" style="margin-left: 10px;">
                <div class="filter-icon-container" @click="setPresetFilter"><img :src="filterSaveIcon" alt=""></div>
              </ToolTip>
            </div>
          </div>
        </template>
      </div>
    </template>
    <div v-else class="mobile-icon" @click="changeLevel">
      <el-image :src="mobileIcon" class="img"/>
      <span v-if="showText" class="text">筛选</span>
    </div>
  </div>
</template>

<script>
import clearIcon from '@/assets/medium/clear.png';
import highlvIcon from '@/assets/orderlist/highlv.png';
import mobileIcon from '@/assets/mobileIcon/search.png';

import PresetFilter from '@/components/Tool/module/PresetFilter/index.vue';
import { mapState } from 'vuex';
// img
import advancedFilterIcon from '@/assets/setting/filter.png';
import advancedFilterIconActive from '@/assets/setting/advancedFilter_active.png';
import presetFilterIcon from '@/assets/setting/quick.png';
import presetFilterIconActive from '@/assets/setting/quick_active.png';
import resetFilterIcon from '@/assets/setting/resetFilter.png';
import filterNumIcon from '@/assets/setting/filterNum.png';
import filterSaveIcon from '@/assets/setting/filterSave.png';

export default {
  name: 'FilterInput',
  components: { PresetFilter },
  model: {
    prop: 'value',
    event: 'changeValue'
  },
  provide() {
    return {
      getActiveTabs: () => {
        return this.presetInfo.activeTabs;
      },
      getFilterData: () => {
        return this.presetInfo.filterData;
      },
      setFilterParams: (data) => {
        this.$emit('setFilterParams', data);
      }
    };
  },
  props: {
    defaultSelectKey: { // 默认选中的key
      type: String,
      default: ''
    },
    value: {
      type: Object,
      default: () => {
        return {};
      }
    },
    showAdvancedFilter: { // 是否展示高级按钮
      type: Boolean,
      default: true
    },
    showReset: {
      type: Boolean,
      default: true
    },
    customFilterList: {
      type: Array,
      default: () => []
    },
    /**
     * filterList
     * @param keyword 字段名
     * @param name 名称
     * @param type 类型,只有input才会出现在普通状态（input、select、date、rangeDate、complexRangeDate、multiMonth）
     * @param options  类型为select或complexRangeDate时使用，下拉选项
     * @param format 类型为rangeDate、date、complexRangeDate时使用，时间格式，默认 yyyy/MM/dd
     * @param timeTypeKeyword 类型为complexRangeDate时，代表下拉选项的字段名称
     * @param tagName 类型为inputSearch时，代表需要被赋值筛选标签的key
    */
    filterList: {
      type: Array,
      default: () => {
        return [];
      }
    },
    isSingleCondition: {// 限制下拉输入单一条件搜索
      type: Boolean,
      default: false
    },
    showMobileIcon: {// 列表移动端仅展示图标
      type: Boolean,
      default: false
    },
    lineFeed: {// 搜索框与按钮换行展示
      type: Boolean,
      default: false
    },
    isShowConfig: { // 是否可以快捷筛选条件
      type: Boolean,
      default: false
    },
    customClass: {
      type: String,
      default: ''
    },
    showText: {
      type: Boolean,
      default: true
    },
    selectValueResult: {
      type: Array,
      default: () => []
    },
    getPresetFilter: {
      type: Function,
      default: null
    },
    presetInfo: {
      type: Object,
      default: null
    }
  },
  data() {
    let selectKey = this.defaultSelectKey || '';
    if (!selectKey) {
      for (let i = 0; i < this.filterList.length; i++) {
        if (this.filterList[i].type === 'input') {
          selectKey = this.filterList[i].keyword;
          break;
        }
      }
    }
    return {
      mobileIcon, advancedFilterIcon, advancedFilterIconActive,
      filterSaveIcon, filterNumIcon,
      presetFilterIcon, presetFilterIconActive,
      resetFilterIcon,
      clearIcon, highlvIcon,
      selectKey: selectKey,
      paramsObj: {},
      rangeDateTime: [],
      level: 'normal', // normal high
      highOptions: false,
      showFilterDialog: false,
      inputFocus: false,
      cache: {},
      isInitFilterConfig: false,
      hasDefaultPresetFilter: false
    };
  },
  computed: {
    ...mapState({
      'showMobilePage': state => state.app.showMobilePage,
      'filterConfig': state => state.filter.filterConfig
    }),
    showFilterTag() {
      const selectValueResult = this.selectValueResult;
      const tagShowStatus = !!(selectValueResult.length && !(selectValueResult.length === 1 && selectValueResult[0].key === this.selectKey));
      this.$emit('filterTagStatus', tagShowStatus);
      return tagShowStatus;
    },
    selectKeyToName() {
      const selectKey = this.selectKey;
      const res = this.filterList.filter(i => {
        return i.keyword === selectKey;
      });
      return res && res[0] && res[0].name ? res[0].name : '';
    }
  },
  watch: {
    defaultSelectKey: {
      handler(newVal) {
        if (newVal) {
          this.selectKey = newVal;
        }
      },
      immediate: true
    }
  },
  methods: {
    queryClick(val) {
      this.$emit('handelClick');
    },
    createNew() {
      this.queryEmpty();
      if (this.$refs.PresetFilterRef) {
        this.$refs.PresetFilterRef.visible = false;
      }
      this.$store.state.medium.filterOpen = true;
    },
    queryEmpty() {
      let selectKey = '';
      for (let i = 0; i < this.filterList.length; i++) {
        if (this.filterList[i].type === 'input') {
          selectKey = this.filterList[i].keyword;
          break;
        }
      }
      this.selectKey = selectKey;
      this.$emit('queryEmpty');
    },
    // 操作
    deleteTag(item) {
      this.$emit('deleteTag', item);
    },
    changeLevel() {
      this.$store.state.medium.filterOpen = !this.$store.state.medium.filterOpen;
    },
    normalChange() {
      if (this.isSingleCondition) {
        this.value = {};
      }
      this.$emit('changeValue', this.value);
    },
    setPresetFilter() {
      if (this.$refs.PresetFilterRef) {
        this.$refs.PresetFilterRef.setData();
      }
    }
  }
};
</script>

<style lang="scss" scoped>
.select-input-component {
  @include flexStyle($align: center);
  &::v-deep {
    .input-width-select-bg {
      &> .el-input__inner {
        background-color: #fff;
      }
    }
    .el-tag.el-tag--info {
      color: #406eff !important;
      background: #eff3fb;
      height: 100%;
      font-size: 12px;
      position: relative;
      max-width: 100%;
      overflow: hidden;
    }
    .el-input-group__append {
      border-left: 1px solid #406EFF;
      border-color: #406EFF;
      padding: 0;
      margin: 0;
      width: 54px;
      overflow: hidden;
      background-color: #406EFF;
      .filter-input-search {
        @include flexStyle(center, center);
        border-radius: 0px;
        border: none;
        padding: 0;
        width: 54px;
        height: 30px;
        cursor: pointer;
        .el-icon-search {
          font-size:16px;
          color: #fff;
        }
      }
    }
    .el-input {
      &>.el-input__inner {
        width: 210px;
      }
    }
    .el-input-group__prepend {
      transition: border-color 0.2s cubic-bezier(0.645, 0.045, 0.355, 1);
      .el-input  {
        .el-input__inner {
          padding-left: 8px;
          border: none;
          width: 115px !important;
          color: #606266;
          font-size: 14px;
        }
      }
    }
  }
}
.tag-container {
  height: 100%;
  display: flex;
  align-items: center;
  margin-top: 8px;
  .filter-icon {
    height: 100%;
    display: flex;
    align-items: center;
    .selected {
      color: #406EFF;
      cursor: pointer;
      height: 24px;
      line-height: 24px;
      background-color: #eff4ff;
      padding: 0 8px;
      border-radius: 4px;
    }
  }
  .filter-icon-container {
    width: 24px;
    height: 24px;
    background: #f3f5fa;
    border-radius: 4px;
    display: flex;
    justify-content: center;
    align-items: center;
    cursor: pointer;
    img {
      width: 14px;
    }
  }

}
.mobile-input-component {
  flex-wrap: wrap;
  .filter-input {
    width: 100%;
    margin-bottom: 12px;
    ::v-deep .el-input__inner {
      width: 100%;
    }
  }
}
.mobile-icon {
  @include flexStyle($align: center, $direction: column);
  margin-right: 24px;
  .text {
    font-size: 10px;
    font-family: PingFang SC, PingFang SC-Regular;
    font-weight: 400;
    color: #aeb6c7;
    line-height: 14px;
    margin-top: 2px;
  }
  .img{
    width: 24px;
    height: 24px;
    img {
      width: 100%;
      height: 100%;
    }
  }
}
.flex {
  @include flexStyle($align: center);
  height: 100%;
  .input-name {
    @include flexStyle($align: center);
    height: 100%;
  }
}
.select-num-tip {
  color: #406EFF;
  cursor: pointer;
}

.filter-tag-group {
  margin-right: 8px;
  color: #333;
  background-color: #EFF3FB;
  border-radius: 2px;
  ::v-deep .el-tag__close {
    color: #999;
  }
  ::v-deep .el-tag__close:hover {
    background-color: #ccc;
  }
}
.select-input-focus {
  &::v-deep {
    .el-input-group__prepend {
      border-color: var(--color-primary);
    }
  }
}
.operate-btn {
  width: 24px;
  height: 24px;
  cursor: pointer;
  margin-left: 12px;
  @include flexStyle(center, center);
  &.active {
    background-color: #EDEEF2;
    border-radius: 4px;
  }
  .operate-icon {
    width: 16px;
    height: 16px;
  }
  .filter-box {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    .filter-label {
      margin-top: 2px;
      font-size: 8px;
      color: #333;
    }
  }
}
</style>
